package cn.bx.bid.ctrl;

import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.User;
import cn.bx.bid.service.UserService;
import cn.bx.bid.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public String login(
            HttpServletRequest request,
            @RequestParam("username") String n,
            @RequestParam(name = "pass", required = true) String p) {
        //request.setCharacterEncoding("utf-8");
        User user = userService.login(n, p);

        // if (n.startsWith("java63") && p.equals("123456")) {
        if (user != null) {
            request.getSession().setAttribute("USER_LOGIN", user);
            //return "welcome.jsp";
            return "forward:/welcome.jsp";
        }
        request.setAttribute("msg", "错误的用户名或者密码！@");
        return "forward:/fail.jsp";
    }

    //不太推荐
//    public String test(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //req.getSession().getServletContext();
//        //ContextLoaderListener;
//
//        req.getRequestDispatcher("/welcome.jsp").forward(req,resp);
//        return null;
//    }

    @GetMapping("toUserAdd")
    public String toAdd() {
        return "useradd";
    }

    //新管理员注册
    @RequestMapping("adminRegister")
    public String register(@ModelAttribute("u") User user) {
//        CharacterEncodingFilter f=null;
//        f.setForceEncoding(true);
//        f.setEncoding("utf-8");
        LogUtil.debug("新管理员：" + user + "保存成功了");
        int r = this.userService.add(user);

        //return "registerOk.jsp";
        //return "/WEB-INF/pages/registerOk.jsp";
        //return "registerOk";
        return "redirect:usersearch.jhtml";
    }

    @GetMapping("usersearch")
    public ModelAndView search(@RequestParam(name = "page", defaultValue = "1") int pageNo, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "startDate", required = false) Date start, @RequestParam(name = "endDate", required = false) Date end) {
        ModelAndView mv = new ModelAndView();
        Page<User> page = this.userService.paging(pageNo, limit, name, start, end);
        mv.addObject("p", page);
        mv.setViewName("adminlist");
        return mv;
//        //HttpServletRequest request,
//        List<User> users = new ArrayList<>();
//        for (int i = 1; i <= 10; i++) {
//            users.add(new User(i * 10L, 1L, "liu" + i, "111" + i, "111" + i, "11111" + i, "2222" + i, null, null));
//        }
//        ModelAndView mv = new ModelAndView();
//        //mv.setViewName("userlist.jsp");
//        mv.setViewName("userlist");
//        mv.addObject("users", users);
//        return mv;
    }
//    public String login(HttpServletRequest request){
//        String name=request.getParameter("")
//        return "";
//    }
    @GetMapping("toUser-update-{id}")
    public String toUpdate(@PathVariable("id") long id, Model m){
        User u=this.userService.get(id);
        m.addAttribute("user",u);//也可以带对象给视图
        return "userupdate";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值
    }

    @ExceptionHandler
    public String exceptionHandler(Exception e){
        LogUtil.error("出现异常",e);
        return "error";
    }
}